<template>
  <v-menu :close-on-content-click="true" location="bottom">
    <template #activator="{ props: p }">
      <v-btn
        v-bind="p"
        :class="['text-no-wrap', buttonClass]"
        :color="color"
        :data-testid="`groupInspectorDrawer-${datatestid}`"
        :disabled="disabled"
        :size="size"
        :variant="variant"
      >
        <v-icon v-if="icon" class="mr-1" :icon="icon" start />
        <span>{{ text }}</span>
        <v-icon :icon="mdiMenuDown" />
      </v-btn>
    </template>
    <v-list density="compact" :style="menuStyle">
      <v-list-item
        v-for="it in items"
        :key="String(it.value)"
        :active="isActive(it)"
        @click="onPick(it.value)"
      >
        <slot :item="it" name="item">
          <v-list-item-title>{{ String(it.title) }}</v-list-item-title>
        </slot>
      </v-list-item>
    </v-list>
  </v-menu>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { mdiMenuDown } from '@mdi/js'

type Item = { title: string | number; value: any }

const props = withDefaults(
  defineProps<{
    modelValue: any
    items: Item[]
    text: string
    datatestid?: string
    icon?: string
    color?: string
    variant?: 'text' | 'tonal' | 'outlined' | 'plain'
    size?: 'x-small' | 'small' | 'default' | 'large'
    buttonClass?: string
    menuMinWidth?: number
    disabled?: boolean
  }>(),
  {
    color: '',
    variant: 'tonal',
    size: 'default',
    buttonClass: '',
    menuMinWidth: 160,
    disabled: false
  }
)

const emit = defineEmits<{
  (e: 'update:modelValue', value: any): void
}>()

const menuStyle = computed(() => ({ minWidth: props.menuMinWidth + 'px' }))

function onPick(val: any) {
  emit('update:modelValue', val)
}

function isActive(it: Item) {
  return it.value === props.modelValue
}
</script>
